'use strict';
const log = require('../logger');
const downloadAlbumCover = require('../downloadAlbumCover');
const getTrackLyrics = require('./getTrackLyrics');
const { writeFileSync } = require('fs-extra');
const afterLyricsFetching = require('./afterLyricsFetching');
/**
 * Add tags to the mp3/flac file.
 *
 * @param {Buffer} decryptedTrackBuffer
 * @param {Object} trackInfos
 * @param {String} saveFilePath
 * @param {Number} numberRetry
 */
const addTrackTags = async (decryptedTrackBuffer, trackInfos, albumInfos, saveFilePath, numberRetry = 0) => {
  log.debug(`Tagging ${trackInfos.SNG_TITLE}, #${trackInfos.SNG_ID}`);
  try {
    const [coverBuffer, trackLyrics] = await Promise.all([downloadAlbumCover(trackInfos), getTrackLyrics(trackInfos)]);

    if (trackLyrics) {
      trackInfos.LYRICS = trackLyrics;
    }
    return await afterLyricsFetching(decryptedTrackBuffer, trackInfos, albumInfos, saveFilePath, coverBuffer);
  } catch (err) {
    log.debug(`Error tagging ${trackInfos.SNG_TITLE}, #${trackInfos.SNG_ID}, Retries: ${numberRetry}, Error: ${err}`);
    if (numberRetry >= 3) {
      writeFileSync(saveFilePath, decryptedTrackBuffer);
      throw err;
    }

    // retry to add tags
    numberRetry++;
    return await addTrackTags(decryptedTrackBuffer, trackInfos, albumInfos, saveFilePath, numberRetry);
  }
};

module.exports = addTrackTags;
